package durst.action.account.include;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;

import durst.action.CalendarBasicAction;
import durst.data.Invite;
import durst.data.UserCalendar;
import durst.data.dao.DaoFactory;
import durst.data.dao.impl.InviteDao;
import durst.data.dao.impl.UserCalendarDao;

@UrlBinding("/action/include/calendars/{$event}")
public class CalendarsIncludeAction extends CalendarBasicAction {
	private boolean json;
	private boolean jumplist;

	@SuppressWarnings("unchecked")
	@DefaultHandler
	public Resolution self() throws SQLException, MapperException {
		List<UserCalendar> cals = ((UserCalendarDao<UserCalendar, Integer>) DaoFactory
				.getInstance().createDao(UserCalendar.class)).getCalendarsForAccountId(
				context.getAccount(), jumplist);

		return addAttributes(cals);
	}

	@SuppressWarnings("unchecked")
	public Resolution invited() throws SQLException, MapperException {
		Calendar now = Calendar.getInstance();
		now.set(Calendar.HOUR_OF_DAY, 0);
		now.set(Calendar.MINUTE, 0);
		now.set(Calendar.SECOND, 0);
		now.set(Calendar.MILLISECOND, 0);

		List<UserCalendar> cals = ((InviteDao<Invite, Integer>) DaoFactory.getInstance().createDao(
				Invite.class)).getInvitedCalendars(context.getAccount(), now.getTime(), jumplist);

		return addAttributes(cals);
	}

	private Resolution addAttributes(List<UserCalendar> cals) throws MapperException {
		context.getRequest().setAttribute("calendarCount", cals.size());

		if (json) {
			context.getRequest().setAttribute("calendars" + "_json",
					JSONMapper.toJSON(cals).render(false));
			return new ForwardResolution("/account/includes/calendar_livesort.jsp");
		}
		Collections.sort(cals, new CalComparator());
		context.getRequest().setAttribute("calendars", cals);
		return new ForwardResolution("/account/includes/calendar_options_fragment.jsp");
	}

	private class CalComparator implements Comparator<UserCalendar> {
		@Override
		public int compare(UserCalendar first, UserCalendar second) {
			if (first.isDef() != second.isDef()) 
				return first.isDef() ? 1 : -1;
			return first.getName().compareTo(second.getName());
		}
	}
	
	public void setJson(boolean json) {
		this.json = json;
	}

	public boolean isJson() {
		return json;
	}

	public void setJumplist(boolean jumplist) {
		this.jumplist = jumplist;
	}

	public boolean isJumplist() {
		return jumplist;
	}
}
